package com.kuang.web.blog;

import com.kuang.pojo.*;
import com.kuang.service.*;
import com.kuang.util.MarkdownUtils;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
//@RequestMapping("/admin")
public class MyBlogController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;
    @Autowired
    private BlogTagService blogTagService;

    @Autowired
    private UserService userService;

    //    首页
    @RequestMapping({"/toindex", "/", ""})
    public String toindex(@RequestParam(defaultValue = "1") Integer pageindex, Model model, HttpSession session) {
        Integer pagesize = 5; // 每页显示10个


        // 当前的页数 pageindex 默认页数为1
        Integer countblog = blogService.countBlog();  // 博客数量
        Integer page = countblog % pagesize == 0 ? countblog / pagesize : (countblog / pagesize) + 1; // 共有多少页
//        Integer co
        int countBlog = blogService.countBlogPublished();  // 多少篇已经发布的博客
        List<Blog> blogList = blogService.selectPageSiteIndexBlog((pageindex - 1) * pagesize, pagesize);//查询所有 博客分页 用于前台首页展示 按照创建时间降序  并且是发布状态的！
        List<Type> typeList = typeService.selectAllType();  // 查出所有分类
        List<BlogTag> blogTagList = blogTagService.selectAllBlogTag();// 查出所有中间表的记录
        List<Tag> tagList = tagService.selectAllTag();  // 查出标签的所有记录
        User user = userService.selectAdminUser(1);  // 查出 管理员用户 用于数据回显 个人简介
        List<Blog> bloglistRecommend = blogService.selectBlogRecommend();  // 查出前三个有推荐的 并且按照时间 观看次数降序的博客
//        System.out.println(user);

//        System.out.println("user = " + user);
        model.addAttribute("countblog", countBlog);
        model.addAttribute("bloglist", blogList);
        model.addAttribute("typelist", typeList);
        model.addAttribute("blogtaglist", blogTagList);
        model.addAttribute("taglist", tagList);
        session.setAttribute("user1", user);   // 多次跳转需要放在session中 首页啊 分类啊！
//        model.addAttribute("user1", user);
        model.addAttribute("page", page);
        model.addAttribute("pageindex", pageindex);
        model.addAttribute("bloglistrecommend", bloglistRecommend);
        return "index";
    }

    @RequestMapping("/totype")
    public String totype(Model model, @RequestParam(defaultValue = "0") Integer maxCountType, HttpSession session) {
        System.out.println(maxCountType);
        User user = userService.selectAdminUser(1);  // 查出 管理员用户 用于数据回显 个人简介
        session.setAttribute("user1", user);// 多次跳转需要放在session中 首页啊 分类啊！
        List<Type> atypeList = typeService.selectAllType();  // 这个是分类表的所有记录，用于前端显示分类名的
        List<VoBlog> voBloglist = new ArrayList<>();
        List<Type> typeList = new ArrayList<>();
        List<Blog> blogList = new ArrayList<>();
        voBloglist = blogService.selectAllBlogCountGroupTypeId();        // 对博客的typeid进行分组 查出分组的个数/分组的分类id，
        List<BlogTag> blogTagList = blogTagService.selectAllBlogTag();  // 查询出所有博客标签表记录
        List<Tag> tagList = tagService.selectAllTag();  // 查询出所有标签表的记录
//         maxCountType = 0;  //  博客拥有分类最多的分类id
        if (maxCountType != 0) { // maxCountType 不为0 说明不是前台传来的参数
            blogList = blogService.selectAllBlogByTypeId(maxCountType);// 当前选择的分类 用id查出对应的博客信息
        } else {
            maxCountType = voBloglist.get(0).getType_id(); // 此时的0代表的是分类最多的博客，其他地方点击分类应该是最多的
            blogList = blogService.selectAllBlogByTypeId(maxCountType);// 当前选择的分类 用id查出对应的博客信息
        }

        for (int i = 0; i < voBloglist.size(); i++) {
            Type type = typeService.selectTypeById(voBloglist.get(i).getType_id());//对博客的typeid进行分组
            // 查出分组的个数/分组的分类id，查出对应的分类id 再从分类表中查出这个对象，再存放到List集合中
            if (type != null) {
                typeList.add(type);

            }
        }
//        System.out.println("voBloglist = " + voBloglist);
//        System.out.println("typeList = " + typeList);
//        System.out.println("maxCountType = " + maxCountType);
//        System.out.println("blogList = " + blogList);
//        System.out.println("atypeList = " + atypeList);
//        System.out.println("blogTagList = " + blogTagList);
//        System.out.println("tagList = " + tagList);
        model.addAttribute("vobloglist", voBloglist);
        model.addAttribute("typelist", typeList);
        model.addAttribute("maxCountType", maxCountType);
        model.addAttribute("bloglist", blogList);
        model.addAttribute("atypelist", atypeList);
        model.addAttribute("blogtaglist", blogTagList);
        model.addAttribute("taglist", tagList);
        return "category";
    }

    @RequestMapping("/totag")
//    @ResponseBody
    public String totag(Model model, HttpSession session, @RequestParam(defaultValue = "0") Integer maxCountTag) {
        List<Tag> tagList = new ArrayList<>();  // 通过博客标签中间表的标签查出 对应的所有标签对象
        List<Blog> blogList = new ArrayList<>();  //  通过中间表的对应的博客id 查出博客对象！
        List<Type> typeList = new ArrayList<>();  //  通过博客里的typeid查出 分类对象
        User user = userService.selectAdminUser(1); //  用于用户的数据回显！
//        System.out.println("maxCountTag = " + maxCountTag);
        List<BlogTag> blogTagList = new ArrayList<>();// 标签博客的个数显示 点击跳转到哪个类型的标签博客
        List<BlogTag> blogTagList1 = blogTagService.selectAllBlogTag();  // 查询出所有博客标签 用于博客下的标签的显示
        List<VoTag> voTags = blogTagService.selectAllBlogTagGroupTagId(); // 分组查出标签id和其对应的个数
        if (maxCountTag == 0) { // 说明是一开始的请求 默认为标签个数最多的
            maxCountTag = voTags.get(0).getTags_id();  // 得到分组后的标签id 个数最多的那个标签id 用于默认搜索！
            blogTagList = blogTagService.selectBlogTagByTagId(maxCountTag);// 根据默认的标签id查出对应的博客id用于数据回显页面展示
//            System.out.println("maxCountTag = " + maxCountTag);
        } else {
            blogTagList = blogTagService.selectBlogTagByTagId(maxCountTag);// 根据默认的标签id查出对应的博客id用于数据回显页面展示

        }
        for (int i = 0; i < blogTagList.size(); i++) {
            Blog blog = blogService.selectAllBlogByMiddleBlogId(blogTagList.get(i).getBlogsId());
            if (blog != null) {  // 防止 中间表的记录没了 还查出博客记录 后面可能发生的空指针
                blogList.add(blog);
            }
        }
        for (int i = 0; i < blogList.size(); i++) {
            Type type = typeService.selectTypeById(blogList.get(i).getTypeId());
            if (type != null) {
                typeList.add(type);
            }
        }
        for (int i = 0; i < voTags.size(); i++) {
            Tag tag = tagService.selectTagById(voTags.get(i).getTags_id());
            if (tag != null) {  // 防止 中间表的记录没了 还查出标签记录 后面可能发生的空指针
                tagList.add(tag);
            }
        }
        model.addAttribute("maxcounttag", maxCountTag);
        model.addAttribute("votaglist", voTags);
        session.setAttribute("user1", user);
        model.addAttribute("taglist", tagList);
        model.addAttribute("bloglist", blogList);
        model.addAttribute("typelist", typeList);
        model.addAttribute("blogtaglist1", blogTagList1);
//        model.addAttribute("blogtaglist", blogTagList);
        return "tag";
    }

    @RequestMapping("/toarchive")
    public String toarchives(Model model) {
        int countBlog = blogService.countBlogPublished();  // 多少篇已经发布的博客
        List<String> yearMonth = blogService.selectGroupYearMonth();  // 先查出博客所有的月份
        HashMap<String, List<Blog>> archivemap = new HashMap<>();
        for (int i = yearMonth.size() - 1; i >= 0; i--) {
            archivemap.put(yearMonth.get(i), blogService.selectBlogByYear(yearMonth.get(i)));
        }
        model.addAttribute("countblog", countBlog);
        model.addAttribute("archivemap", archivemap);
        return "archive";
    }

    @RequestMapping("/toblogdetail")
//    @ResponseBody
    public String toblogdetail(Model model, HttpSession session, Integer blogid) {
        User user1 = userService.selectAdminUser(1); // 用于侧边栏的数据回显
        System.out.println("blogid = " + blogid);
        blogService.updateBlogViews(blogid); // 修改博客浏览次数
        Blog blog = blogService.selectBlogById(blogid);
//        MarkdownUtils.markdownToHtmlExtensions
        blog.setContent(MarkdownUtils.mdToHtml(blog.getContent()));
        List<Comment> commentList = commentService.selectAllCommentByBlogId(blogid);
        model.addAttribute("blog", blog);
        session.setAttribute("user1", user1);
        System.out.println("user1 = " + user1);
        for (Comment comment : commentList) {
            System.out.println("comment = " + comment);
        }
        model.addAttribute("commentlist", commentList);
        return "detail";
    }

    //    @ResponseBody
    @RequestMapping("/toindexsearch")
    public String toindexsearch(String keywords, @RequestParam(defaultValue = "1") Integer pageindex, Model model, HttpSession session) {
        List<Type> typeList1 = typeService.selectTypeByKeyWords(keywords);// 根据 关键字查出的分类对象，然后我们获取这个分类的id查询对应的博客
        Integer pagesize = 6; // 每页显示10个
        // 当前的页数 pageindex 默认页数为1
        Integer typeid = null;
        System.out.println("keywords = " + keywords);
        System.out.println("typeList1 = " + typeList1);
        if (typeList1.size() != 0) {  // 有可能一种情况，就是通过关键字查不出id 而你又用这个空的集合对象去点 typeid 就会报错
            typeid = typeList1.get(0).getId(); // 获取通过关键字查出来的分类id
        }
        int countblog = blogService.selectPageSiteIndexBlogSearchCount((pageindex - 1) * pagesize, pagesize, keywords, typeid);
        Integer page = countblog % pagesize == 0 ? countblog / pagesize : (countblog / pagesize) + 1; // 共有多少页
        int countBlog = blogService.countBlogPublished();  // 多少篇已经发布的博客
//      =======
// 查询方法 分页 加上关键字 分类id查询
        List<Blog> blogList = blogService.selectPageSiteIndexBlogSearch((pageindex - 1) * pagesize, pagesize, keywords, typeid);
        for (Blog blog : blogList) {
            System.out.println("blog = " + blog);
        }
//        ===========
        List<Type> typeList = typeService.selectAllType();  // 查出所有分类
        List<BlogTag> blogTagList = blogTagService.selectAllBlogTag();// 查出所有中间表的记录
        List<Tag> tagList = tagService.selectAllTag();  // 查出标签的所有记录
        User user = userService.selectAdminUser(1);  // 查出 管理员用户 用于数据回显 个人简介
        List<Blog> bloglistRecommend = blogService.selectBlogRecommend();  // 查出前三个有推荐的 并且按照时间 观看次数降序的博客
        model.addAttribute("countblog", countblog);
        model.addAttribute("bloglist", blogList);
        model.addAttribute("typelist", typeList);
        model.addAttribute("blogtaglist", blogTagList);
        model.addAttribute("taglist", tagList);
        session.setAttribute("user1", user);   // 多次跳转需要放在session中 首页啊 分类啊！
        model.addAttribute("page", page);
        model.addAttribute("pageindex", pageindex);
        model.addAttribute("bloglistrecommend", bloglistRecommend);
        System.out.println("page = " + page);
        System.out.println("pageindex = " + pageindex);
        return "indexsearch";
    }
}
